#pragma once
#include <stdio.h>
#include <inttypes.h>
#include <sys/msg.h>

// 消息队列8k左右有问题，>8k直接错误
#define ONE_MSG_MAX_LEN 8000
#pragma pack(1)
// messege data struct
struct msgDtStct
{
    long rmtId;                    // remote id
    long sndId;                    // send id
    uint16_t msgCmd;               // messege command id
    uint16_t msgSize;              // messege max size < 8k.
    char msgData[ONE_MSG_MAX_LEN]; // 8k左右有问题，>8k直接错误
}; // __attribute__((packed));gcc标准，其他地方还不好用。用#pragma
#pragma pack()
#define ONE_MSG_HEAD_LEN (offsetof(struct msgDtStct, msgData))

int msgDtPackRmtId(struct msgDtStct *msgdata, long inRmt);
int msgDtPackCmd(struct msgDtStct *msgdata, uint16_t incmd);
int msgDtPackMem(struct msgDtStct *msgdata, const void *indata, uint16_t dsize);
int msgDtPackStr(struct msgDtStct *msgdata, const char *indata);

int msgDtPackIdMem(struct msgDtStct *msgdata, const void *indata, uint16_t dsize, long inRmt, uint16_t incmd);
int msgDtPackIdStr(struct msgDtStct *msgdata, const char *indata, long inRmt, uint16_t incmd);

struct msgOptStct
{
    int msgfd;
    key_t msgkey;
    long myId; // 自己的ID，用于接收消息
};
// 消息队列，多个消息接收器同时接收同一个ID，只有一个消息接收器能收到数据。
int msgOptInit(struct msgOptStct *msgopt, key_t inkey, long inId);
int msgOptQuit(struct msgOptStct *msgopt);
int msgOptSend(struct msgOptStct *msgopt, struct msgDtStct *indata);
int msgOptSendMem(struct msgOptStct *msgopt, const void *indata, uint16_t dsize, long inRmt, uint16_t incmd);
int msgOptSendStr(struct msgOptStct *msgopt, const char *indata, long inRmt, uint16_t incmd);
// messege operator receive
int msgOptRcv(struct msgOptStct *msgopt, struct msgDtStct *indata);